<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/3/26
 * Time: 16:43
 */

namespace app\common\library;


use app\common\exception\CustomerException;
use app\common\model\SellerAppointment;
use app\common\util\RandomUtil;

class DDingUtil
{

    const DD_HOST_NAME = "https://saas-openapi.dding.net/v2";

    const CLIENT_ID = "2521da3ceb314b108b596929";

    const CLIENT_SECRET = "10f6132cbbc6217b0e946fd2d4e1872e";

    private static function _sendRequest($url, $params, $type)
    {
        $responseString = RequestUtil::getInstance()->sendRequest($url, $params, $type);
        $responseData = json_decode($responseString, true);
        if (!empty($responseData['ErrNo'])) {
            if ($responseData['ErrNo'] === 5018 || $responseData['ErrNo'] === 5006) throw new CustomerException($responseData['ErrNo']);
            throw new CustomerException($responseData['ErrMsg']);
        }
        return $responseData;
    }

    private static function _getAccessToken()
    {
        $url = self::DD_HOST_NAME . "/access_token";
        return self::_sendRequest($url, [
            "client_id" => self::CLIENT_ID,
            "client_secret" => self::CLIENT_SECRET
        ], RequestUtil::REQUEST_POST_JSON);
    }

    public static function getAccessToken()
    {
        $ddConfig = model("config")->get(2);
        if (empty($ddConfig)) {
            $responseData = self::_getAccessToken();
            model("config")->insert([
                'id' => 2,
                'title' => 'dding门锁配置',
                'content' => json_encode([
                    'access_token' => $responseData['access_token'],
                    'expires_time' => $responseData['expires_time']
                ])
            ]);
            $ddConfig = model("config")->get(2);
            $config = json_decode($ddConfig['content'], true);
        } else {
            $config = json_decode($ddConfig['content'], true);
            if ($config['expires_time'] < time()) {
                $responseData = self::_getAccessToken();
                $config = [
                    'access_token' => $responseData['access_token'],
                    'expires_time' => $responseData['expires_time']
                ];
                model("config")->where('id', 2)->update([
                    'content' => json_encode($config)
                ]);
            }
        }
        return $config["access_token"];
    }

    public static function getHousePassword($houseId, $uuid, $phone, $passwordId)
    {
        try {
            $expireTime = time() + 7200;
            $url = self::DD_HOST_NAME . "/update_password_without_center";
            $responseData = self::_sendRequest($url, [
                "access_token" => self::getAccessToken(),
                "home_id" => $houseId,
                "uuid" => $uuid,
                "CMD" => 2,
                "name" => "员工密码",
                "phonenumber" => $phone,
                "permission_end" => $expireTime,
                "password_id" => $passwordId
            ], RequestUtil::REQUEST_POST);
            $responseData['invalid_time'] = date('Y-m-d H:i:s', $expireTime);
            return $responseData;
        } catch (CustomerException $e) {
            if ($e->getMessage() === "5006") {
                return self::addPassword($houseId, $uuid, $phone);
            } else {
                throw $e;
            }
        }
    }

    public static function addPassword($homeId, $uuid, $phone)
    {
        try {
            $expireTime = time() + 7200;
            $url = self::DD_HOST_NAME . "/add_password_without_center";
            $responseData = self::_sendRequest($url, [
                "access_token" => self::getAccessToken(),
                "home_id" => $homeId,
                "uuid" => $uuid,
                "CMD" => 2,
                "name" => "员工密码",
                "permission_end" => $expireTime,
            ], RequestUtil::REQUEST_POST);
            $responseData['invalid_time'] = date('Y-m-d H:i:s', $expireTime);
            return $responseData;
        } catch (CustomerException $e) {
            if ($e->getMessage() === "5018") {
                return self::getHousePassword($homeId, $uuid, $phone, 3001);
            } else {
                throw $e;
            }
        }
    }

}